<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SQL Schema 校验工具 by lxx</title>
    <style>

        body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow-y: auto; /* 允许垂直滚动 */
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
        }
        /* .container 样式调整 */
        .container {
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            max-width: 600px;
            margin: 20px auto; /* 垂直方向上自动居中 */
            display: flex;
            flex-direction: column;
        }
        h1 {
            text-align: center;
            margin-bottom: 24px;
            font-size: 24px;
            color: #333;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
        }
        .form-group input[type="text"],
        .form-group input[type="file"],
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 16px;
        }
        .form-group input[type="file"] {
            padding: 3px;
        }
        .form-group textarea {
            resize: none;
            height: 150px;
        }
        .form-group input[type="checkbox"] {
            margin-right: 10px;
        }
        .btn-container {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        .btn {
            padding: 12px 20px;
            background-color: #007BFF;
            color: #fff;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            text-align: center;
            transition: background-color 0.3s;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-clear {
            background-color: #dc3545;
        }
        .btn-download {
            background-color: #28a745;
            display: none;
        }.btn-crete {
            background-color: #d9441e;
            display: none;
        }
        .result-div {
            background: #f8f8f8;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: monospace;
        }
        .highlight-red {
            color: red;
            font-weight: bold;
        }
        .highlight-green {
            color: green;
            font-weight: bold;
        }

        .back-to-top {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: #007BFF;
            color: #fff;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            font-size: 24px;
            transition: background-color 0.3s;
        }
        .back-to-top:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>SQL Schema 校验工具 by lxx</h1>
    <div class="form-group">
        <label for="fileInput">选择文件:</label>
        <input type="file" id="fileInput" multiple>
    </div>
    <div class="form-group">
        <label for="schemaInput">输入 Schema:</label>
        <input type="text" id="schemaInput" placeholder="请输入 Schema">
    </div>
    <div class="form-group">
        <label for="tablespaceCheck">
            <input type="checkbox" id="tablespaceCheck">
            校验表空间
        </label>
    </div>
<!--    <div class="form-group">-->
<!--        <label for="obCheck">-->
<!--            <input type="checkbox" id="obCheck">-->
<!--            是否 OB 数据库-->
<!--        </label>-->
<!--    </div>-->
    <div class="btn-container">
        <button id="validateButton" class="btn">开始校验</button>
        <button id="clearButton" class="btn btn-clear">清空校验结果</button>
        <button id="downloadButton" class="btn btn-download">下载错误文件</button>
        <button id="creteValidSql" class="btn btn-crete">生成评审sql</button>

    </div>

    <div class="form-group mt-4">
        <label for="resultDiv">校验结果:</label>
        <div id="resultDiv" class="result-div"></div>
    </div>


</div>
<button class="back-to-top" id="backToTopButton">⬆️</button>
<script>
    document.getElementById('validateButton').addEventListener('click', function() {
        const fileInput = document.getElementById('fileInput');
        const schemaInput = document.getElementById('schemaInput').value;
        const tablespaceCheck = document.getElementById('tablespaceCheck').checked;
        //获取下载评审按钮按钮
        const creteValidSql = document.getElementById('creteValidSql');
        // const obCheck = document.getElementById('obCheck').checked;
        const resultDiv = document.getElementById('resultDiv');

        if (fileInput.files.length === 0) {
            alert("请选择要验证的文件");
            return;
        }
        if (!schemaInput) {
            alert("请输入要校验的 Schema");
            return;
        }
        creteValidSql.style.display = 'block';
        const formData = new FormData();
        for (const file of fileInput.files) {
            formData.append('files', file);
        }
        formData.append('schema', schemaInput);
        formData.append('checkTablespace', tablespaceCheck);
        // formData.append('isOB', obCheck);

        fetch('/sql-validator/validateSchema', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                const formattedResult = formatResult(data.result);
                resultDiv.innerHTML = formattedResult;

                const downloadButton = document.getElementById('downloadButton');

                if (data.errorFiles && data.errorFiles.length > 0) {
                    downloadButton.style.display = 'block';
                    downloadButton.onclick = () => {
                        // 使用 async/await 来确保每个文件都能正确下载
                        async function downloadFiles() {
                            for (const file of data.errorFiles) {
                                try {
                                    const response = await fetch(`/sql-validator/download/${file}`);
                                    const blob = await response.blob();
                                    const url = window.URL.createObjectURL(blob);
                                    const link = document.createElement('a');
                                    link.href = url;
                                    link.download = file;
                                    document.body.appendChild(link);
                                    link.click();
                                    document.body.removeChild(link);
                                } catch (error) {
                                    console.error('下载文件时出错:', error);
                                }
                            }
                        }
                        downloadFiles();
                    };
                } else {
                    downloadButton.style.display = 'none';
                }

                if (data.validFiles && data.validFiles.length > 0) {
                    // downloadButton.style.display = 'block';
                    creteValidSql.onclick = () => {
                        // 使用 async/await 来确保每个文件都能正确下载
                        async function downloadValidFiles() {
                            for (const file of data.validFiles) {
                                try {
                                    const response = await fetch(`/sql-validator/downloadValid/${file}`);
                                    const blob = await response.blob();
                                    const url = window.URL.createObjectURL(blob);
                                    const link = document.createElement('a');
                                    link.href = url;
                                    link.download = file;
                                    document.body.appendChild(link);
                                    link.click();
                                    document.body.removeChild(link);
                                } catch (error) {
                                    console.error('下载文件时出错:', error);
                                }
                            }
                        }
                        downloadValidFiles();
                    };
                }
            })
            .catch(error => {
                console.error('Error:', error);
                resultDiv.innerHTML = '<span class="highlight-red">校验过程中出错，请查看控制台日志。</span>';
            });
    });

    document.getElementById('clearButton').addEventListener('click', function() {
        document.getElementById('resultDiv').innerHTML = '';
        document.getElementById('downloadButton').style.display = 'none';
        document.getElementById('creteValidSql').style.display = 'none';
    });

    function formatResult(result) {
        const redPatterns = [
            /文件: .*\.sql - 缺少表空间语句/g,
            /文件: .*\.sql - Schema 缺失/g,
            /文件: .*\.sql - Schema 错误/g,
            /文件: .*\.sql - sql缺少using index tablespace关键字/g,
            /文件: .*\.sql - sql缺少online关键字/g,
            /文件: .*\.sql - 建表语句字段类型缺少数值范围/g,
            /SQL语句为：/g,
            /异常字段：/g
        ];
        const greenPattern = /文件: .*\.sql - 验证通过/g;
        let formattedResult = result;

        redPatterns.forEach(pattern => {
            formattedResult = formattedResult.replace(pattern, match => `<span class="highlight-red">${match}</span>`);
        });

        formattedResult = formattedResult.replace(greenPattern, match => `<span class="highlight-green">${match}</span>`);

        return formattedResult;
    }


    document.getElementById('backToTopButton').addEventListener('click', function() {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
</script>
</body>
</html>
